<template>
  <div>
    <!-- 可点击的缩略图 -->
    <img
      :src="src"
      :alt="alt"
      :style="thumbnailStyle"
      @click="showPreview"
      class="image-thumbnail"
    />

    <!-- 自定义预览弹窗 -->
    <Teleport to="body">
      <Transition name="fade">
        <div v-if="visible" class="custom-image-preview" @click="hidePreview">
          <div class="preview-mask"></div>
          <div class="preview-content" @click.stop>
            <img :src="src" :alt="alt" class="preview-image" />
            <div class="preview-close" @click="hidePreview">
              <el-icon :size="24"><Close /></el-icon>
            </div>
          </div>
        </div>
      </Transition>
    </Teleport>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { Close } from '@element-plus/icons-vue'

interface Props {
  src: string
  alt?: string
  width?: string
  height?: string
  fit?: string
}

const props = withDefaults(defineProps<Props>(), {
  alt: '',
  width: '180px',
  height: '60px',
  fit: 'cover'
})

const visible = ref(false)

const thumbnailStyle = {
  width: props.width,
  height: props.height,
  objectFit: props.fit,
  borderRadius: '4px',
  cursor: 'pointer',
  transition: 'transform 0.2s',
}

const showPreview = () => {
  visible.value = true
  document.body.style.overflow = 'hidden'
}

const hidePreview = () => {
  visible.value = false
  document.body.style.overflow = ''
}
</script>

<style scoped>
.image-thumbnail {
  display: block;
}

.image-thumbnail:hover {
  transform: scale(1.05);
  opacity: 0.9;
}

.custom-image-preview {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100vw;
  height: 100vh;
  z-index: 99999999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.preview-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.8);
  z-index: 99999999;
}

.preview-content {
  position: relative;
  z-index: 100000000;
  max-width: 90vw;
  max-height: 90vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

.preview-image {
  max-width: 100%;
  max-height: 90vh;
  object-fit: contain;
  border-radius: 8px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
}

.preview-close {
  position: fixed;
  top: 40px;
  right: 40px;
  width: 44px;
  height: 44px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 100000001;
  transition: all 0.3s;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.2);
}

.preview-close:hover {
  background-color: #fff;
  transform: scale(1.1);
}

/* 淡入淡出动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.fade-enter-to,
.fade-leave-from {
  opacity: 1;
}
</style>

